import { Component, inject, OnInit } from '@angular/core';
import { DelonFormModule, SFSchema, SFSelectWidgetSchema, SFUISchema } from '@delon/form';
import { _HttpClient } from '@delon/theme';
import { NzButtonModule } from 'ng-zorro-antd/button';
import { NzSafeAny } from 'ng-zorro-antd/core/types';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalRef } from 'ng-zorro-antd/modal';
import { NzSpinModule } from 'ng-zorro-antd/spin';
import { Api } from 'src/app/shared/api/api';
import { AUTHORIZATION_GRANT_TYPE, CLIENT_AUTHENTICATION_METHOD } from 'src/app/shared/constant/common-constant';
import { ResponseCode } from 'src/app/shared/response.code';

@Component({
  selector: 'app-auth2-client-edit',
  templateUrl: './client-edit.component.html',
  imports: [NzSpinModule, DelonFormModule, NzButtonModule]
})
export class ClientEditComponent implements OnInit {
  record: NzSafeAny = {};
  schema: SFSchema = { properties: {} };
  ui: SFUISchema = {
    '*': {
      spanLabel: 6,
      spanControl: 10,
      grid: { span: 24 }
    }
  };
  scopeList: NzSafeAny[] = [];

  private readonly modal = inject(NzModalRef);
  private readonly msgSrv = inject(NzMessageService);
  public readonly http = inject(_HttpClient);

  ngOnInit(): void {
    this.getScope();
  }

  // 初始化表单，在获取完部门树数据之后再初始化
  initSchema() {
    this.schema = {
      properties: {
        clientId: {
          type: 'string',
          title: 'clientId'
        },
        clientName: {
          type: 'string',
          title: '名称'
        },
        clientSecret: {
          type: 'string',
          title: '密码'
        },
        clientSecretExpiresAt: {
          type: 'string',
          title: '密码过期时间',
          format: 'date-time'
        },
        clientAuthenticationMethods: {
          type: 'string',
          title: '验证方法',
          enum: CLIENT_AUTHENTICATION_METHOD,
          ui: {
            widget: 'select',
            mode: 'multiple'
          } as SFSelectWidgetSchema
        },
        authorizationGrantTypes: {
          type: 'string',
          title: '授权类型',
          enum: AUTHORIZATION_GRANT_TYPE,
          ui: {
            widget: 'select',
            mode: 'multiple'
          } as SFSelectWidgetSchema
        },
        redirectUris: {
          type: 'string',
          title: '授权码模式回调地址',
          ui: {
            widget: 'textarea',
            autosize: true,
            placeholder: '多个地址，使用逗号隔开',
            grid: {
              span: 24
            },
            readOnly: true
          }
        },
        postLogoutRedirectUris: {
          type: 'string',
          title: '退出重定向地址',
          ui: {
            widget: 'textarea',
            autosize: true,
            placeholder: '多个地址，使用逗号隔开',
            grid: {
              span: 24
            }
          }
        },
        scopes: {
          type: 'string',
          title: '授权范围',
          enum: this.scopeList,
          ui: {
            widget: 'select',
            mode: 'tags'
          } as SFSelectWidgetSchema
        },
        requireAuthorizationConsent: {
          type: 'boolean',
          title: '是否需要授权确认',
          default: true
        },
        accessTokenTimeToLive: {
          type: 'number',
          title: 'accessToken存活时长(小时)'
        },
        authorizationCodeTimeToLive: {
          type: 'number',
          title: '授权码存活时长(分钟)'
        },
        deviceCodeTimeToLive: {
          type: 'number',
          title: '设备码存活时长(分钟)'
        },
        refreshTokenTimeToLive: {
          type: 'number',
          title: 'refreshToken存活时长(天)'
        },
        reuseRefreshTokens: {
          type: 'boolean',
          title: '是否重用 Refresh Token',
          default: false
        }
      },
      required: ['clientId', 'clientName', 'clientSecret', 'scopes', 'clientAuthenticationMethods', 'authorizationGrantTypes']
    };
  }

  getScope() {
    this.http.get(Api.BaseScopeApi).subscribe(res => {
      console.log(res);
      if (res.data) {
        let temp: NzSafeAny[] = [];
        res.data.forEach((item: NzSafeAny) => {
          temp.push({ label: item.description, value: item.name });
        });
        this.scopeList = temp;
        this.initSchema();
      } else {
        this.msgSrv.warning('没有配置过scope,请先配置scope');
      }
    });
  }
  save(value: NzSafeAny) {
    console.log(value);
    if (this.record.id) {
      this.http.put(Api.BaseClientApi, value).subscribe((res: NzSafeAny) => {
        if (res) {
          if (res.code === ResponseCode.SUCCESS) {
            this.msgSrv.success('修改成功');
            this.modal.close(true);
          } else {
            this.msgSrv.warning(res.message);
          }
        } else {
          this.msgSrv.error('修改失败，未知错误');
        }
      });
    } else {
      this.http.post(Api.BaseClientApi, value).subscribe((res: NzSafeAny) => {
        if (res) {
          if (res.code === ResponseCode.SUCCESS) {
            this.msgSrv.success('保存成功');
            this.modal.close(true);
          } else {
            this.msgSrv.warning(res.message);
          }
        } else {
          this.msgSrv.error('保存失败，未知错误');
        }
      });
    }
  }

  close() {
    this.modal.destroy();
  }
}
